"use client";

import React, { useState, useEffect, useCallback } from "react";
import {
  Card,
  Row,
  Col,
  Statistic,
  Progress,
  Table,
  Badge,
  Tag,
  Alert,
  Spin,
  Button,
  Space,
  List,
  Avatar,
  Typography,
  Divider,
  Tabs,
  App,
} from "antd";
import {
  UserOutlined,
  TeamOutlined,
  DatabaseOutlined,
  MonitorOutlined,
  ClockCircleOutlined,
  ExclamationCircleOutlined,
  CheckCircleOutlined,
  ThunderboltOutlined,
  WarningOutlined,
} from "@ant-design/icons";
import { system } from "@/forent-api/api";
import { useRouter } from "next/navigation";
import {
  ConcurrencyMonitor,
  getStatusColor,
  RealTimeMonitor,
  SystemHealth,
  SystemStats,
  tableColumns,
} from "./tools";
import { formatMemory } from "@/utils/tools";

const { Text } = Typography;

const SystemHomeContent: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [systemStats, setSystemStats] = useState<SystemStats | null>(null);
  const [systemHealth, setSystemHealth] = useState<SystemHealth | null>(null);
  const [realTimeMonitor, setRealTimeMonitor] =
    useState<RealTimeMonitor | null>(null);
  const [concurrencyMonitor, setConcurrencyMonitor] =
    useState<ConcurrencyMonitor | null>(null);
  const [refreshing, setRefreshing] = useState(false);
  const { message } = App.useApp();
  const router = useRouter();

  // 获取系统统计数据
  const fetchSystemStats = useCallback(async () => {
    try {
      const response = await system.getSystemStats();
      setSystemStats(response.data);
    } catch (error) {
      message.error("获取系统统计失败");
    }
  }, [message]);

  // 获取系统健康状态
  const fetchSystemHealth = useCallback(async () => {
    try {
      const response = await system.getSystemHealth();
      setSystemHealth(response.data);
    } catch (error) {
      message.error("获取系统健康状态失败");
    }
  }, [message]);

  // 获取实时监控数据
  const fetchRealTimeMonitor = useCallback(async () => {
    try {
      const response = await system.getRealTimeMonitor();
      setRealTimeMonitor(response.data);
    } catch (error) {
      message.error("获取实时监控数据失败");
    }
  }, [message]);

  // 获取并发监控数据
  const fetchConcurrencyMonitor = useCallback(async () => {
    try {
      const response = await system.getConcurrencyMonitor();
      setConcurrencyMonitor(response.data);
    } catch (error) {
      message.error("获取并发监控数据失败");
    }
  }, [message]);

  // 初始化数据
  const initializeData = useCallback(async () => {
    setLoading(true);
    try {
      await Promise.all([
        fetchSystemStats(),
        fetchSystemHealth(),
        fetchRealTimeMonitor(),
        fetchConcurrencyMonitor(),
      ]);
    } finally {
      setLoading(false);
    }
  }, [
    fetchSystemStats,
    fetchSystemHealth,
    fetchRealTimeMonitor,
    fetchConcurrencyMonitor,
  ]);

  // 页面初始化
  useEffect(() => {
    initializeData();

    // 设置定时刷新
    const realTimeInterval = setInterval(() => {
      fetchRealTimeMonitor();
    }, 30000); // 30秒刷新一次实时数据

    const concurrencyInterval = setInterval(() => {
      fetchConcurrencyMonitor();
    }, 60000); // 60秒刷新一次并发数据

    return () => {
      clearInterval(realTimeInterval);
      clearInterval(concurrencyInterval);
    };
  }, [initializeData, fetchRealTimeMonitor, fetchConcurrencyMonitor]);

  // 格式化运行时间
  const formatUptime = (seconds: number) => {
    const days = Math.floor(seconds / 86400);
    const hours = Math.floor((seconds % 86400) / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    return `${days}天 ${hours}时 ${minutes}分`;
  };

  // 快速操作导航
  const handleQuickNavigation = (path: string) => {
    router.push(path);
  };

  return (
    <Spin spinning={loading} tip="加载系统数据中..." size="large">
      <div className="">
        {/* 并发监控卡片 */}
        <Row gutter={8} className="mb-2">
          <Col span={8}>
            <Card>
              <Statistic
                title="当前并发数"
                value={concurrencyMonitor?.current.concurrency || 0}
                prefix={<ThunderboltOutlined />}
                valueStyle={{
                  color:
                    concurrencyMonitor?.current.status === "high"
                      ? "#ff4d4f"
                      : concurrencyMonitor?.current.status === "medium"
                      ? "#fa8c16"
                      : "#52c41a",
                }}
                suffix="req/min"
              />
              <div className="mt-2">
                <Text type="secondary">
                  成功率: {concurrencyMonitor?.current.successRate || 100}% |
                  响应: {concurrencyMonitor?.current.avgResponseTime || 0}ms
                </Text>
              </div>
            </Card>
          </Col>
          <Col span={8}>
            <Card>
              <Statistic
                title="峰值并发数"
                value={concurrencyMonitor?.peak.maxConcurrency || 0}
                prefix={<MonitorOutlined />}
                valueStyle={{ color: "#722ed1" }}
                suffix="req/min"
              />
              <div className="mt-2">
                <Text type="secondary">
                  峰值时间:{" "}
                  {concurrencyMonitor?.peak.peakTime
                    ? new Date(
                        concurrencyMonitor.peak.peakTime
                      ).toLocaleTimeString()
                    : "暂无"}
                </Text>
              </div>
            </Card>
          </Col>
          <Col span={8}>
            <Card>
              <Statistic
                title="系统负载"
                value={concurrencyMonitor?.loadLevel.description || "低负载"}
                prefix={<DatabaseOutlined />}
                valueStyle={{
                  color:
                    concurrencyMonitor?.loadLevel.level === "high"
                      ? "#ff4d4f"
                      : concurrencyMonitor?.loadLevel.level === "medium"
                      ? "#fa8c16"
                      : "#52c41a",
                }}
              />
              <div className="mt-2">
                <Badge
                  status={
                    concurrencyMonitor?.loadLevel.level === "high"
                      ? "error"
                      : concurrencyMonitor?.loadLevel.level === "medium"
                      ? "warning"
                      : "success"
                  }
                  text={`负载等级: ${
                    concurrencyMonitor?.loadLevel.level || "low"
                  }`}
                />
              </div>
            </Card>
          </Col>
        </Row>

        {/* 系统统计概览卡片 */}
        <Row gutter={8} className="mb-2">
          <Col span={6}>
            <Card>
              <Statistic
                title="系统用户"
                value={systemStats?.users.total || 0}
                prefix={<UserOutlined />}
                valueStyle={{ color: "#1890ff" }}
              />
              <div className="mt-2">
                <Text type="secondary">
                  活跃: {systemStats?.users.active || 0} | 停用:{" "}
                  {systemStats?.users.inactive || 0}
                </Text>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="机构部门"
                value={systemStats?.departments.total || 0}
                prefix={<TeamOutlined />}
                valueStyle={{ color: "#52c41a" }}
              />
              <div className="mt-2">
                <Text type="secondary">
                  市级: {systemStats?.departments.city || 0} | 区县:{" "}
                  {systemStats?.departments.county || 0}
                </Text>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="今日操作"
                value={systemStats?.todayLogs.total || 0}
                prefix={<MonitorOutlined />}
                valueStyle={{ color: "#fa8c16" }}
              />
              <div className="mt-2">
                <Text type="secondary">
                  成功: {systemStats?.todayLogs.success || 0} | 失败:{" "}
                  {systemStats?.todayLogs.error || 0}
                </Text>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="定时任务"
                value={systemStats?.timerTasks.total || 0}
                prefix={<ClockCircleOutlined />}
                valueStyle={{ color: "#722ed1" }}
              />
              <div className="mt-2">
                <Text type="secondary">
                  运行: {systemStats?.timerTasks.active || 0} | 停用:{" "}
                  {systemStats?.timerTasks.inactive || 0}
                </Text>
              </div>
            </Card>
          </Col>
        </Row>

        {/* 系统健康状态 */}
        <Row gutter={8} className="mb-2">
          <Col span={12}>
            <Card
              title={
                <>
                  <DatabaseOutlined className="mr-2" />
                  系统健康状态
                </>
              }
            >
              <Row gutter={[8, 8]}>
                <Col span={8}>
                  <div className="text-center">
                    <Badge
                      className="font-bold"
                      status={getStatusColor(
                        systemHealth?.database.status || "default"
                      )}
                      text="数据库状态"
                    />
                    <div className="mt-1">
                      <Text type="secondary">
                        响应时间: {systemHealth?.database.responseTime || 0}ms
                      </Text>
                    </div>
                  </div>
                </Col>
                <Col span={8}>
                  <div className="text-center">
                    <Badge
                      className="font-bold"
                      status={getStatusColor(
                        systemHealth?.application.status || "default"
                      )}
                      text="应用状态"
                    />
                    <div className="mt-1">
                      <Text type="secondary">
                        环境: {systemHealth?.application.environment || "N/A"}
                      </Text>
                    </div>
                  </div>
                </Col>
                <Col span={8}>
                  <div className="text-center">
                    <Badge
                      status="success"
                      text="服务器状态"
                      className="font-bold"
                    />
                    <div className="mt-1">
                      <Text type="secondary">
                        运行时间:{" "}
                        {formatUptime(systemHealth?.server.uptime || 0)}
                      </Text>
                    </div>
                  </div>
                </Col>
              </Row>

              <Divider />

              <Row gutter={[16, 8]} className="flex items-start">
                {/* 左侧：内存使用情况 */}
                <Col span={16}>
                  <Text strong>内存使用情况:</Text>
                  <div className="mt-2">
                    <Row gutter={[16, 8]}>
                      {/* 系统内存使用 */}
                      <Col span={12}>
                        <div className="mb-2">
                          <Text type="secondary">系统内存使用</Text>
                        </div>
                        <Progress
                          percent={
                            systemHealth?.server.memory?.usagePercent || 0
                          }
                          status={
                            (systemHealth?.server.memory?.usagePercent || 0) >
                            80
                              ? "exception"
                              : (systemHealth?.server.memory?.usagePercent ||
                                  0) > 60
                              ? "normal"
                              : "active"
                          }
                          strokeColor={{
                            "0%": "#52c41a",
                            "60%": "#faad14",
                            "80%": "#ff4d4f",
                            "100%": "#ff4d4f",
                          }}
                        />
                        <Text type="secondary" className="text-xs">
                          已用:{" "}
                          {formatMemory(systemHealth?.server.memory?.used || 0)}{" "}
                          / 总计:{" "}
                          {formatMemory(
                            systemHealth?.server.memory?.total || 0
                          )}
                          ({systemHealth?.server.memory?.usagePercent || 0}%)
                        </Text>
                      </Col>

                      {/* Node.js 进程内存使用 */}
                      <Col span={12}>
                        <div className="mb-2">
                          <Text type="secondary">Node.js 进程内存</Text>
                        </div>
                        <Progress
                          percent={
                            systemHealth?.server.memory?.processUsagePercent ||
                            0
                          }
                          status="active"
                          strokeColor="#722ed1"
                        />
                        <Text type="secondary" className="text-xs">
                          RSS:{" "}
                          {formatMemory(systemHealth?.server.memory?.rss || 0)}(
                          {systemHealth?.server.memory?.processUsagePercent ||
                            0}
                          %)
                        </Text>
                      </Col>
                    </Row>

                    {/* 核心系统信息 */}
                    <div className="mt-3 p-2 bg-gray-50 rounded text-xs">
                      <Row gutter={[12, 4]}>
                        <Col span={12}>
                          <Text type="secondary">JS堆内存: </Text>
                          <Text
                            strong
                            className={
                              (systemHealth?.server.memory?.heapUsagePercent ||
                                0) > 90
                                ? "text-red-600"
                                : (systemHealth?.server.memory
                                    ?.heapUsagePercent || 0) > 70
                                ? "text-orange-500"
                                : "text-blue-600"
                            }
                          >
                            {systemHealth?.server.memory?.heapUsagePercent || 0}
                            %
                          </Text>
                        </Col>
                        <Col span={12}>
                          <Text type="secondary">CPU核心数: </Text>
                          <Text strong className="text-green-600">
                            {systemHealth?.server.cpuInfo?.cores || 0} 核
                          </Text>
                        </Col>
                      </Row>
                    </div>
                  </div>
                </Col>

                {/* 右侧：应用版本信息 */}
                <Col span={8}>
                  <Text strong>应用版本信息:</Text>
                  <div className="mt-2 space-y-3">
                    <div className="flex flex-col space-y-2">
                      <div className="flex items-center justify-between">
                        <Text type="secondary">Node.js版本:</Text>
                        <Tag color="blue">
                          {systemHealth?.server.nodeVersion || "N/A"}
                        </Tag>
                      </div>

                      <div className="flex items-center justify-between">
                        <Text type="secondary">应用版本:</Text>
                        <Tag color="green">
                          {systemHealth?.application.version || "N/A"}
                        </Tag>
                      </div>

                      <div className="flex items-center justify-between">
                        <Text type="secondary">运行环境:</Text>
                        <Tag
                          color={
                            systemHealth?.application.environment ===
                            "production"
                              ? "red"
                              : "orange"
                          }
                        >
                          {systemHealth?.application.environment || "N/A"}
                        </Tag>
                      </div>

                      <div className="flex items-center justify-between">
                        <Text type="secondary">系统平台:</Text>
                        <Tag color="purple">
                          {systemHealth?.server.platform || "N/A"}
                        </Tag>
                      </div>

                      <div className="flex items-center justify-between">
                        <Text type="secondary">进程ID:</Text>
                        <Tag color="geekblue">
                          {systemHealth?.server.pid || "N/A"}
                        </Tag>
                      </div>
                    </div>
                  </div>
                </Col>
              </Row>
            </Card>
          </Col>

          <Col span={12}>
            <Card
              title={
                <>
                  <DatabaseOutlined className="mr-2" />
                  数据库信息
                </>
              }
            >
              <Row gutter={[16, 12]}>
                {/* 数据库基础信息 */}
                <Col span={24}>
                  <Row gutter={[8, 8]}>
                    <Col span={12}>
                      <div className="flex items-center justify-between">
                        <Text type="secondary">数据库类型:</Text>
                        <Tag color="blue">
                          {systemHealth?.database.type || "N/A"}
                        </Tag>
                      </div>
                    </Col>
                    <Col span={12}>
                      <div className="flex items-center justify-between">
                        <Text type="secondary">数据库版本:</Text>
                        <Tag color="green">
                          {systemHealth?.database.version || "N/A"}
                        </Tag>
                      </div>
                    </Col>
                    <Col span={12}>
                      <div className="flex items-center justify-between">
                        <Text type="secondary">数据库大小:</Text>
                        <Tag color="orange">
                          {systemHealth?.database.size || "N/A"}
                        </Tag>
                      </div>
                    </Col>
                    <Col span={12}>
                      <div className="flex items-center justify-between">
                        <Text type="secondary">数据表数量:</Text>
                        <Tag color="purple">
                          {systemHealth?.database.tableCount || 0} 张
                        </Tag>
                      </div>
                    </Col>
                  </Row>
                </Col>

                <Divider className="my-3" />

                {/* 连接状态信息 */}
                <Col span={24}>
                  <Text strong className="block mb-2">
                    连接状态:
                  </Text>
                  <Row gutter={[8, 8]}>
                    <Col span={8}>
                      <div className="text-center p-2 bg-blue-50 rounded">
                        <div className="text-lg font-bold text-blue-600">
                          {systemHealth?.database.connections?.total || 0}
                        </div>
                        <Text type="secondary" className="text-xs">
                          总连接数
                        </Text>
                      </div>
                    </Col>
                    <Col span={8}>
                      <div className="text-center p-2 bg-green-50 rounded">
                        <div className="text-lg font-bold text-green-600">
                          {systemHealth?.database.connections?.active || 0}
                        </div>
                        <Text type="secondary" className="text-xs">
                          活跃连接
                        </Text>
                      </div>
                    </Col>
                    <Col span={8}>
                      <div className="text-center p-2 bg-gray-50 rounded">
                        <div className="text-lg font-bold text-gray-600">
                          {systemHealth?.database.connections?.idle || 0}
                        </div>
                        <Text type="secondary" className="text-xs">
                          空闲连接
                        </Text>
                      </div>
                    </Col>
                  </Row>
                </Col>

                <Divider className="my-3" />

                {/* 响应时间 */}
                <Col span={24}>
                  <div className="flex items-center justify-between">
                    <Text strong>响应时间:</Text>
                    <Tag
                      color={
                        (systemHealth?.database.responseTime || 0) > 100
                          ? "red"
                          : (systemHealth?.database.responseTime || 0) > 50
                          ? "orange"
                          : "green"
                      }
                    >
                      {systemHealth?.database.responseTime || 0} ms
                    </Tag>
                  </div>
                </Col>
              </Row>
            </Card>
          </Col>
        </Row>

        {/* 实时监控数据 */}
        <Row gutter={8}>
          <Col span={12}>
            <Card
              title={
                <>
                  <WarningOutlined className="mr-2" />
                  最近错误日志
                </>
              }
            >
              {realTimeMonitor?.recentErrors &&
              realTimeMonitor.recentErrors.length > 0 ? (
                <List
                  size="small"
                  dataSource={realTimeMonitor.recentErrors.slice(0, 5)}
                  renderItem={(item, index) => (
                    <List.Item key={index}>
                      <List.Item.Meta
                        avatar={
                          <Avatar
                            icon={<ExclamationCircleOutlined />}
                            style={{ backgroundColor: "#ff4d4f" }}
                          />
                        }
                        title={
                          <div>
                            <Text strong>{item.module}</Text>
                            <Tag color="red" style={{ marginLeft: 8 }}>
                              错误
                            </Tag>
                          </div>
                        }
                        description={
                          <div>
                            <Text type="secondary">{item.operation_name}</Text>
                            <br />
                            <Text type="secondary">
                              用户: {item.user_name || "系统"}
                            </Text>
                            <br />
                            <Text type="secondary" ellipsis>
                              错误信息: {item.error_msg}
                            </Text>
                          </div>
                        }
                      />
                    </List.Item>
                  )}
                />
              ) : (
                <div className="text-center py-8">
                  <CheckCircleOutlined
                    style={{ fontSize: 48, color: "#52c41a" }}
                  />
                  <div className="mt-2">
                    <Text>系统运行正常，暂无错误日志</Text>
                  </div>
                </div>
              )}
            </Card>
          </Col>

          <Col span={12}>
            <Card
              title={
                <>
                  <MonitorOutlined className="mr-2" />
                  活跃用户
                </>
              }
            >
              {realTimeMonitor?.activeUsers &&
              realTimeMonitor.activeUsers.length > 0 ? (
                <List
                  size="small"
                  dataSource={realTimeMonitor.activeUsers.slice(0, 5)}
                  renderItem={(item, index) => (
                    <List.Item key={index}>
                      <List.Item.Meta
                        avatar={
                          <Avatar
                            icon={<UserOutlined />}
                            style={{ backgroundColor: "#1890ff" }}
                          />
                        }
                        title={<Text strong>{item.user_name}</Text>}
                        description={
                          <div>
                            <Text type="secondary">
                              操作次数: {item.operation_count}
                            </Text>
                            <br />
                            <Text type="secondary">
                              最后活动:{" "}
                              {new Date(item.last_operation).toLocaleString()}
                            </Text>
                          </div>
                        }
                      />
                    </List.Item>
                  )}
                />
              ) : (
                <div className="text-center py-8">
                  <UserOutlined style={{ fontSize: 48, color: "#d9d9d9" }} />
                  <div className="mt-2">
                    <Text type="secondary">暂无活跃用户数据</Text>
                  </div>
                </div>
              )}
            </Card>
          </Col>
        </Row>

        {/* 最近任务执行情况 */}
        <Row gutter={8} className="mt-2">
          <Col span={24}>
            <Card
              title={
                <>
                  <ClockCircleOutlined className="mr-2" />
                  最近任务执行情况
                </>
              }
            >
              {realTimeMonitor?.taskExecutions &&
              realTimeMonitor.taskExecutions.length > 0 ? (
                <Table
                  size="small"
                  dataSource={realTimeMonitor.taskExecutions}
                  pagination={{ pageSize: 5, size: "small" }}
                  columns={tableColumns()}
                />
              ) : (
                <div className="text-center py-8">
                  <ClockCircleOutlined
                    style={{ fontSize: 48, color: "#d9d9d9" }}
                  />
                  <div className="mt-2">
                    <Text type="secondary">暂无任务执行记录</Text>
                  </div>
                </div>
              )}
            </Card>
          </Col>
        </Row>
      </div>
    </Spin>
  );
};

export default function SystemHome() {
  return (
    <div className="rounded-[10px] px-2 overflow-scroll h-[calc(100vh-80px)] ">
      <SystemHomeContent />
    </div>
  );
}
